package com.changhong.wlyspectrum.MainTestActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.changhong.wlyspectrum.NetWork.HttpMethods;
import com.changhong.wlyspectrum.R;
import com.changhong.wlyspectrum.utils.MetaDataBean;
import com.changhong.wlyspectrum.utils.MyConfig;
import com.google.gson.Gson;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by Mr_tao
 * on 2017/3/9.
 */
public class TestRecordActivity extends Activity{
    private final static String TAG = "TestRecordActivity";
    private ImageView mBackIv;
    private TextView mChooseTv;
    private TextView mUpTv;
    private TextView mDownTv;
    private ListView mListView;
    private RecordAdapter mAdapter;
    private String user_id;
    private String token;
    private JSONArray jsonArray = null;
    private String collectionId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_record_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_test_record);

        Intent intent = getIntent();
        collectionId = intent.getStringExtra("collectionId");

        SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        user_id = mypref.getString("user_id", "default");
        token = mypref.getString("token", "default");

        GetRecord();

        InitUi();
    }

    private void InitUi() {
        mBackIv = (ImageView)findViewById(R.id.record2test);
        mBackIv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mChooseTv = (TextView)findViewById(R.id.choose_tv);
        mChooseTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

        mUpTv = (TextView)findViewById(R.id.up);
        mDownTv = (TextView)findViewById(R.id.down);

        mUpTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

        mDownTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

        mListView = (ListView)findViewById(R.id.record_lt);
        mAdapter = new RecordAdapter();
    }

    public Handler getRecordHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mListView.setAdapter(mAdapter);
                    break;
                case 1:
                    Toast.makeText(getApplicationContext(),getString(R.string.no_record),Toast.LENGTH_SHORT).show();
                    break;
                case 98:
                    Toast.makeText(getApplicationContext(),getString(R.string.getrecord_fail),Toast.LENGTH_SHORT).show();
                    break;
                case 99:
                    Toast.makeText(getApplicationContext(),getString(R.string.network_error),Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    class RecordAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(), R.layout.record_list_item, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            JSONObject metadata = null;
            JSONObject data = null;
            String time = null;
            try {
                metadata = new JSONObject(jsonArray.getString(position));
                data = new JSONObject(metadata.getString("metadata"));
                time = metadata.getString("creation");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Gson gson = new Gson();
            MetaDataBean Data = gson.fromJson(data.toString(), MetaDataBean.class);
            /*String s = getString(R.string.wet) +  Data.getAttributes().getWater() +"%" + " "+
                    getString(R.string.acidity) +  Data.getAttributes().getAcidity()  +"%"+ " "+
                    getString(R.string.starch)  +  Data.getAttributes().getStarch()  +"%"+ " "+
                    getString(R.string.sugar)  +  Data.getAttributes().getSugar() +"%";*/
            HashMap<String ,String> hashMap = new HashMap<>();
            /*String value = Data.getAttri().get("amino");
            if(value == null){
                return null;
            }*/
            hashMap =  (HashMap<String, String>) Data.getAttri().clone();
            if(hashMap.isEmpty()){
                Log.e(TAG,"hashmap is null");
            }
            String s = "";
            Set<Map.Entry<String, String>> set = hashMap.entrySet();
            Iterator<Map.Entry<String, String>> iterator2 = set.iterator();
            while(iterator2.hasNext()){
                Map.Entry<String, String> entry = iterator2.next();
                s = s + entry.getKey() + ":" + entry.getValue() + ";";
            }
            holder.rTextView.setText(s);
            holder.tTextView.setText(MyConfig.stampToDate(time));
            return convertView;
        }

    }

    class ViewHolder{
        TextView rTextView;
        TextView tTextView;

        public ViewHolder(View view){
            rTextView = (TextView)view.findViewById(R.id.rTextView);
            tTextView = (TextView)view.findViewById(R.id.tTextView);
            view.setTag(this);
        }
    }

    private void GetRecord(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                String columns = "metadata,creation";
                String start = "0";
                String max = "20";
                String orderBy = "desc";
                String path = "/scio/" + collectionId +"/records" + "?columns=" + columns + "&start=" + start + "&max=" + max +"&flag=1" + "&orderBy=" + orderBy;
                try{
                    Response response = HttpMethods.TGetResponse(path,user_id,token);
                    if(response.isSuccessful()){
                        String result = response.body().string();
                        Log.e(TAG,"result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        Log.e(TAG,"code----->" + code);
                        if(code.compareTo("0") == 0){
                            String jsonobj = jsonObject.getString("jsonObj");
                            jsonArray = new JSONArray(jsonobj);
                            if(jsonArray != null){
                                getRecordHandler.sendMessage(Message.obtain(getRecordHandler, 0));
                            }else{
                                getRecordHandler.sendMessage(Message.obtain(getRecordHandler, 1));
                            }
                        }else{
                            getRecordHandler.sendMessage(Message.obtain(getRecordHandler, 98));
                        }
                    }else{
                        getRecordHandler.sendMessage(Message.obtain(getRecordHandler, 99));
                    }
                } catch (IOException e) {
                    getRecordHandler.sendMessage(Message.obtain(getRecordHandler, 99));
                    e.printStackTrace();
                } catch (JSONException e) {
                    getRecordHandler.sendMessage(Message.obtain(getRecordHandler, 99));
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
